# 作者：要努力，努力，再努力
# 开发时间：2022/4/28 8:50

import os

filename = 'student3.txt'


def main():
    while True:
        menu()
        try:
            choice = int(input('请选择：'))
        except:
            print('您输入信息有误，请重新输入')
            continue
        if choice == 0:
            isexit = input('您确定要退出系统？y/n')
            if isexit == 'y':
                break
            else:
                continue
        elif choice == 1:
            insert()
        elif choice == 2:
            delete()
        elif choice == 3:
            modify()
        elif choice == 4:
            select()
        elif choice == 5:
            sort()
        elif choice == 6:
            total()
        elif choice == 7:
            show()
        else:
            print('您输入有误，请重新输入')
            continue


def menu():
    print('============================学生信息管理系统=============================')
    print('----------------------------选择菜单------------------------------------')
    print('\t\t\t\t1.录入学生信息')
    print('\t\t\t\t2.删除学生信息')
    print('\t\t\t\t3.修改学生信息')
    print('\t\t\t\t4.查询学生信息')
    print('\t\t\t\t5.排序')
    print('\t\t\t\t6.统计学生总人数')
    print('\t\t\t\t7.显示所有学生信息')
    print('\t\t\t\t0.退出系统')
    print('----------------------------------------------------------------------')


def insert():
    student_lst = []
    while True:
        try:
            id = int(input('请输入学生ID：'))
        except:
            print('输入有误，请重新输入')
            continue
        name = input('请输入学生姓名：')
        try:
            english = int(input('请输入学生英语成绩：'))
            python = int(input('请输入学生python成绩'))
            java = int(input('请输入学生java成绩'))
        except:
            print('输入成绩必须为整数，请重新输入')
            continue
        student_lst.append({'id': id, 'name': name, 'english': english, 'python': python, 'java': java})
        answer = input('是否继续录入？y/n')
        if answer == 'y':
            continue
        else:
            break
    save(student_lst)


def save(lst):
    # lst 为列表，lst 的每一项为字典形式
    try:
        file = open(filename, 'a', encoding='utf-8')
    except:
        file = open(filename, 'w', encoding='utf-8')
    for item in lst:
        file.write(str(item) + '\n')
    file.close()
    print('学生信息保存成功')


def delete():
    show()
    if os.path.exists(filename):
        while True:
            flag = False
            try:
                student_id = int(input('请输入要删除的学生ID:'))
            except:
                print('学生ID需为整数格式，请重新输入')
            student_list = []
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            if student_list:
                with open(filename, 'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in student_list:
                        d = dict(eval(item))
                        if d['id'] != student_id:
                            wfile.write(str(d) + '\n')
                        else:
                            flag = True
                            print('学生信息已删除')
            if flag:
                print(f'没有找到学生{student_id}信息')
            else:
                print(f'已经删除学生{student_id}的信息')
            answer = input('是否继续删除？y/n')
            if answer == 'y':
                continue
            else:
                show()
                break
    else:
        print('没有学生信息')
        return


def modify():
    if os.path.exists(filename):
        while True:
            flag = False
            try:
                student_id = int(input('请输入需要修改的id:'))
            except:
                print('请输入整型')
                continue
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_lst = rfile.readlines()
            if student_lst:
                with open(filename, 'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in student_lst:
                        d = dict(eval(item))
                        if d['id'] != student_id:
                            wfile.write(str(d) + '\n')
                        else:
                            print('找到学生信息，请修改！')
                            try:
                                d['english'] = int(input('请输入英语成绩：'))
                                d['name'] = input('请输入学生姓名：')
                                d['python'] = int(input('请输入python成绩'))
                                d['java'] = int(input('请输入java'))
                            except:
                                print('输入信息错误，请重新输入')
                                continue
                            wfile.write(str(d) + '\n')
                            flag = True
            if flag:
                print('修改学生信息成功')
            else:
                print('没有找到学生信息')
            answer = input('是否继续修改？y/n')
            if answer == 'y':
                continue
            else:
                show()
                break
    else:
        print('无数据')
        return


def select():
    if os.path.exists(filename):
        while True:
            student_query = []
            try:
                student_id = int(input('请输入学生ID:'))
            except:
                print('输入信息有误')
                continue
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            if student_list:
                for item in student_list:
                    d = dict(eval(item))
                    if d['id'] == student_id:
                        student_query.append(d)
            if student_query:
                show_student(student_query)
            else:
                print(f'没有找到id为{student_id}的学生信息')
            answer = input('是否继续查询？y/n')
            if answer == 'y':
                continue
            else:
                break
    else:
        print('无信息')
        return


def sort():
    if os.path.exists(filename):
        while True:
            flag = False
            # 拿数据
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            student_new = []
            for item in student_list:
                student_new.append(dict(eval(item)))
            # 升序还是降序
            try:
                asc_or_dec = int(input('请选择：1.升序 2. 降序'))
            except:
                print('输入错误')
                continue
            if asc_or_dec == 1:
                asc_or_dec_bool = False
            else:
                asc_or_dec_bool = True
            # 按照哪个成绩排序
            try:
                mode = int(input('请选择：1. 按English 2. 按Python 3. 按 Java 4. 按 总成绩'))
            except:
                print('不是整数，输入无效')
                continue
            flag = True
            if mode == 1:
                student_new.sort(key=lambda x: int(x['english']), reverse=asc_or_dec_bool)
            elif mode == 2:
                student_new.sort(key=lambda x: int(x['python']), reverse=asc_or_dec_bool)
            elif mode == 3:
                student_new.sort(key=lambda x: int(x['java']), reverse=asc_or_dec_bool)
            elif mode == 4:
                student_new.sort(key=lambda x: int(x['english']) + int(x['python']) + int(x['java']),
                                 reverse=asc_or_dec_bool)
            else:
                print('输入不在范围内')
                continue
            if flag:
                show_student(student_new)
                print('学生信息排序成功')
            else:
                print('没有学生信息')
    else:
        print('没有学生信息')
        return


def total():
    if os.path.exists(filename):
        with open(filename,'r',encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        print(f'学生人数为{len(student_list)}')
    else:
        print('无学生信息')
        return


def show():
    if os.path.exists(filename):
        show_studentlist = []
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        for item in student_list:
            show_studentlist.append(dict(eval(item)))
        show_student(show_studentlist)
    else:
        print('没有学生信息')
        return


def show_student(lst):
    if len(lst):
        format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t'
        print(format_title.format('ID', 'name', 'english', 'python', 'java', '总成绩'))
        format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t'
        for item in lst:
            # print(item)
            # print(item.get('id'))
            print(format_data.format(item.get('id'),
                                     item.get('name'),
                                     item.get('english'),
                                     item.get('python'),
                                     item.get('java'),
                                     int(item.get('english')) + int(item.get('python')) + int(item.get('java'))))

    else:
        print('无数据')


if __name__ == '__main__':
    main()
